package com.example.demospringboot.netty.http.handler;

import com.example.demospringboot.netty.http.exception.HttpException;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author chenlei
 * @date 2020/1/8
 * @description
 **/
public class HttpResponseHandler extends SimpleChannelInboundHandler<FullHttpResponse> {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private FullHttpResponse receiveMsg;

    public FullHttpResponse getReceiveMsg() {
        return receiveMsg;
    }

    public void setReceiveMsg(FullHttpResponse receiveMsg) {
        this.receiveMsg = receiveMsg;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse res) throws Exception {
        if(!res.decoderResult().isSuccess()){
            String message = "http请求失败";
            logger.error(message);
            throw new HttpException(message);
        }
        this.receiveMsg = res.copy();
        logger.info(res.content().toString(CharsetUtil.UTF_8));
    }

    /*@Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,HttpMethod.GET,"/user/add",Unpooled.copiedBuffer("i am coming",CharsetUtil.UTF_8));
        request.headers().set(org.apache.http.HttpHeaders.CONTENT_TYPE,"text/plain;charset=utf-8");
        ctx.writeAndFlush(request);
        super.channelActive(ctx);
    }*/
}
